﻿using UnityEngine;

namespace Nomo.UnityCoreModule
{
    /// <summary>
    /// 音效处理者。
    /// </summary>
    public class SoundHandler : MonoBehaviour
    {
        private AudioSource _audioSource;
        private float       _volume;

        /// <summary>
        /// 音量。
        /// </summary>
        public float Volume { get => _volume; set => AudioSource.volume = (_volume = Mathf.Clamp01(value)) * SoundManager.Instance.VolumeScale; }

        private AudioSource AudioSource
        {
            get
            {
                if (!_audioSource)
                {
                    (_audioSource = gameObject.AddComponent<AudioSource>()).loop = false;
                }

                return _audioSource;
            }
        }

        /// <summary>
        /// 是否正在播放？
        /// </summary>
        public bool IsPlaying => AudioSource && AudioSource.isPlaying;

        /// <summary>
        /// 播放音效。
        /// </summary>
        /// <param name="key">音效名。</param>
        /// <param name="volume">音量。</param>
        public void Play(string key, float volume)
        {
            var audioClip = AudioProvider.Instance.GetAudioClip(key);
            if (!audioClip)
            {
                return;
            }
            name             = key;
            AudioSource.clip = audioClip;
            Volume           = volume;
            AudioSource.Play();
        }

        /// <summary>
        /// 停止音效。
        /// </summary>
        public void Stop()
        {
            AudioSource.Stop();
        }

        private void OnVolumeScaleChanged()
        {
            if (AudioSource)
            {
                AudioSource.volume = Volume * SoundManager.Instance.VolumeScale;
            }
        }

        private void OnEnable()
        {
            if (Common.AppAlive)
            {
                SoundManager.Instance.VolumeScaleChanged += OnVolumeScaleChanged;
            }
        }

        private void OnDisable()
        {
            if (Common.AppAlive)
            {
                SoundManager.Instance.VolumeScaleChanged -= OnVolumeScaleChanged;
            }
        }
    }
}
